//
//  ComposeViewController.swift
//  sina_yl
//
//  Created by 袁量 on 2017/5/24.
//  Copyright © 2017年 袁量. All rights reserved.
//

import UIKit
import SVProgressHUD
class ComposeViewController: UIViewController {

    @IBOutlet weak var picCollectionView: PicPickerCollectionView!
    @IBOutlet weak var textView: ComposeTextView!
    @IBOutlet weak var collectionViewHeightConstraint: NSLayoutConstraint!
    @IBOutlet weak var toolsBottomConstraint: NSLayoutConstraint!
    lazy var titleView : ComposeTitleView = ComposeTitleView()
    lazy var emoticonVc : EmoticonController = EmoticonController {[weak self] (emoticon) in
        self?.insertEmoticon(emoticon : emoticon)
    }
    var images : [UIImage] = [UIImage]()
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpNavBar()
        setUpNotifications()
     
    }
    deinit {
         NotificationCenter.default.removeObserver(self)
    }
    @IBAction func picPicker() {
        textView.resignFirstResponder()
        collectionViewHeightConstraint.constant = UIScreen.main.bounds.size.height * 0.65
        UIView.animate(withDuration: 0.5) {  
            self.view.layoutIfNeeded()
        }
    }
    @IBAction func emoticonBtnClick() {
        emoticonBtnTouch()
    }
}
// MARK: - 设置 UI
extension ComposeViewController {
    fileprivate func setUpNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(ComposeViewController.close))
            navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .plain, target: self, action: #selector(ComposeViewController.sendMessage))
        titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
        navigationItem.titleView = titleView
    }
    fileprivate func setUpNotifications() {
        NotificationCenter.default.addObserver(self, selector: #selector(ComposeViewController.UIKeyboardWillChangeFrame(note:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ComposeViewController.presentPicPickerVC), name: NSNotification.Name(rawValue: PicPickerAddPhotoNote), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ComposeViewController.removePhoto(info:)), name: NSNotification.Name(rawValue: PicPickerRemovePhotoNote), object: nil)
    }
}
// MARK: - 响应事件
extension ComposeViewController {
    
    @objc fileprivate func close() {
        dismiss(animated: true) {}
    }
    @objc fileprivate func sendMessage() {
        // 0.键盘退出
        textView.resignFirstResponder()
        
        // 1.获取发送微博的微博正文
        let statusText = textView.getEmoticonString()
        
        // 2.定义回调的闭包
        let finishedCallback = { (isSuccess : Bool) -> () in
            if !isSuccess {
                SVProgressHUD.showError(withStatus: "发送微博失败")
                return
            }
            SVProgressHUD.showSuccess(withStatus: "发送微博成功")
            self.dismiss(animated: true, completion: nil)
        }
        
        // 3.获取用户选中的图片
        if let image = images.first {
            NetworkingTools.shareInstance.sendStatus(statusText: statusText, image: image, isSuccess: finishedCallback)
        } else {
            NetworkingTools.shareInstance.sendStatus(statusText: statusText, isSuccess: finishedCallback)
        }
    }
    func UIKeyboardWillChangeFrame(note : Notification) {
//        print(note.userInfo ?? "什么都没有")
        let duration = note.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! TimeInterval
        
        let endFrame = (note.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
        
        let y = endFrame.origin.y
        
        let margin = UIScreen.main.bounds.size.height - y
        toolsBottomConstraint.constant = margin
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }
    }
    func presentPicPickerVC() {
        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            return
        }
        let picPicker = UIImagePickerController()
        picPicker.delegate = self
        picPicker.sourceType = .photoLibrary
        present(picPicker, animated: true) { } 
    }
    func removePhoto(info : NSNotification) {
        guard let image = info.object as? UIImage else {
            return
        }
        guard let index = images.index(of: image) else {
            return
        }
        images.remove(at: index)
        picCollectionView.images = images
    }
    func emoticonBtnTouch() {
        textView.resignFirstResponder()
        
        textView.inputView = textView.inputView != nil ? nil : emoticonVc.view
        
        textView.becomeFirstResponder()
    }
    func insertEmoticon(emoticon : Emoticon) {
        textView.insertEmoticon(emoticon)
        textViewDidChange(textView!)
    }
    
}
extension ComposeViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        // 2.将选中的照片添加到数组中 
        images.append(image)
        print(image)
        // 3.将数组赋值给collectionView,让collectionView自己去展示数据
        picCollectionView.images = images
//        picCollectionView.backgroundView = UIImageView(image: image, highlightedImage: nil)

        picker.dismiss(animated: true) { }
    }
}
// MARK: - 控制器的代理方法
extension ComposeViewController : UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        self.textView.placeHolderLabel.isHidden = textView.hasText
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText

    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
    }

}
